import math

from django.db import connection

from app.service import inventory, sms
from libs import time_helper
from libs.db import DB
from libs.form import Page


def notify_shop_managers_to_take_inventory(cursor):
    dh = DB('table_shop_address', conn=cursor)
    filters = {'is_community': 1}
    total = dh.count(filters)
    size = 100
    total_page = math.ceil(total / size)
    fields = ['id', 'tel_remind']
    for i in range(0, total_page):
        pn = i + 1
        page = Page(pn, size)
        db_shops = dh.order_by('id asc').page(page).find(fields, filters)
        for db_shop in db_shops:
            db_shop_id = db_shop.get('id')
            db_tel = db_shop.get('tel_remind')
            if type(db_tel) is str and len(db_tel) == 11:
                db_inventory_id = inventory.get_a_record_of_current_month_inventory(cursor, 1, db_shop_id)
                if db_inventory_id == 0:
                    subject_code = '{}-{}'.format(db_shop_id, 1)
                    sms.send_sms(subject_code, 1, db_tel)


def notify_warehouse_managers_to_take_inventory(cursor):
    dh = DB('cs_admins', conn=cursor)
    filters = {'role_id': 2, 'tel!=""': None, 'status': 1, 'w_id>0': None}
    total = dh.count(filters)
    size = 100
    total_page = math.ceil(total / size)
    fields = ['id', 'tel', 'w_id']
    for i in range(0, total_page):
        pn = i + 1
        page = Page(pn, size)
        db_shops = dh.order_by('id asc').page(page).find(fields, filters)
        for db_shop in db_shops:
            db_tel = db_shop.get('tel')
            db_w_id = db_shop.get('w_id')
            if type(db_tel) is str and len(db_tel) == 11:
                db_inventory_id = inventory.get_a_record_of_current_month_inventory(cursor, 2, db_w_id)
                if db_inventory_id == 0:
                    subject_code = '{}-{}'.format(db_w_id, 2)
                    sms.send_sms(subject_code, 1, db_tel)


def notify_managers_to_take_inventory():
    day_num_str = time_helper.ts_to_time_str(time_format='%d')
    task_date_num = time_helper.get_offset_date_of_the_month(-2)
    if int(day_num_str) == task_date_num:
        with connection.cursor() as cursor:
            notify_shop_managers_to_take_inventory(cursor)
            notify_warehouse_managers_to_take_inventory(cursor)
